<template>
	<view class="WhereTo">
		<view class="header">
			你想去哪里？
		</view>
		<view class="content-box">
			<scroll-view scroll-x="true" class="itembox" :scroll-into-view="currentScrollView" scroll-with-animation>
				<view class="header-scroll-box">
					<view v-for="(item, index) in CusData" :key="index" class="header-card" :id="'card-' + index"
						@click="setActiveLoop(index)" :class="{ 'active-card': activeLoopIndex === index }"
						:style="{ backgroundImage: `url(${imageUrl + item.loop_img_cover})`, backgroundSize: 'cover', backgroundPosition: 'center' }">
						<text class="title">
							<!-- {{ item.loop_name }} -->
						</text>
						<text class="describe">
							<!-- {{ item.loop_content }} -->
						</text>
					</view>
				</view>
			</scroll-view>
			<scroll-view scroll-y="true" class="itemboy">
				<view v-if="activeLoopIndex !== null" class="loopCard" @click="ShowToGopop(item)"
					v-for="(item, index) in CusData[activeLoopIndex]?.data" :key="index">
					<image :src="imageUrl + item.img.split(',')[0]" mode="aspectFill"></image>
					<view class="container-box">
						<text class="title">{{ item.name }}</text>
						<text class="describe">{{ item.desc }}</text>
					</view>
					<label class="radio">
						<radio :value="item.scenic_id" :checked="selectedDestinations.includes(item.scenic_id)"
							color="#790000" @click.stop="toggleDestination(item)" />
					</label>
				</view>
			</scroll-view>
		</view>
		<view class="footer-button" v-if="selectedDestinations.length >= 1">
			<view class="header-box">
				<text>已选目的地：</text>
				<scroll-view scroll-x="true" class="itembox">
					<view class="selected-card">
						<view v-for="(destination, index) in selectedDestinations" :key="index" class="card">
							<text class="Number">{{ index + 1 }}</text>
							<text class="destination">{{ getDestinationNameById(destination) }}</text>
							<text class="cancel" @click="removeDestination(destination)">+</text>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="button" @click="toDIYtripOrTripRecommend">创建行程</view>
		</view>
	</view>
	<toGopopVue ref="isToGopop" :popupData="selectedItem"></toGopopVue>
</template>
<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		imageUrl
	} from '../../../config/request/request';
	import {
		GetscenicList,
		GetgetRecommendation
	} from '../../../config/API/Customize';
	import toGopopVue from './components/toGopop.vue';

	const CusData = ref([]);
	const isToGopop = ref(null); // 控制弹窗
	const selectedItem = ref(null);
	const activeLoopIndex = ref(0); // 用来记录当前选中的环线
	const selectedDestinations = ref([]); // 用来记录已选目的地
	const currentScrollView = ref(''); // 用于控制 scrollIntoView 的目标
	onLoad(async () => {
		const data = await GetscenicList();
		CusData.value = data.data;
		console.log('定制信息==》==》', CusData.value);
	});

	const setActiveLoop = (index) => {
		activeLoopIndex.value = index; // 更新选中的环线索引
		currentScrollView.value = 'card-' + index; // 设置 scroll-into-view 的值为点击的卡片 id
	};
	const toggleDestination = (item) => {
		console.log('打印', item.scenic_id)
		const destinationId = item.scenic_id; // 这里存储的是目的地的 ID
		const index = selectedDestinations.value.indexOf(destinationId);
		console.log(index, '123123', selectedDestinations.value)
		if (index === -1) {
			selectedDestinations.value.push(destinationId);
		} else {
			selectedDestinations.value.splice(index, 1);
		}
	};

	// 根据 ID 获取目的地的名称
	const getDestinationNameById = (id) => {
		console.log('idididid', id);
		for (const loop of CusData.value) {
			console.log("loop", loop);
			if (!loop.data || !Array.isArray(loop.data)) {
				console.warn(`Loop ${loop.loop_id} has no valid data.`);
				continue; // Skip this loop if data is not an array or is missing
			}
			const destination = loop.data.find(item => item.scenic_id === id);
			if (destination) return destination.name;
		}
		return '未知地点'; // Return a default value if nothing found
	};

	// 移除已选目的地
	const removeDestination = (destinationId) => {
		const index = selectedDestinations.value.indexOf(destinationId);
		if (index !== -1) {
			selectedDestinations.value.splice(index, 1);
		}
	};

	// 展示弹窗
	const ShowToGopop = (item) => {
		console.log('item', item);
		isToGopop.value.showPopup();
		selectedItem.value = item; // 设置为当前点击的 item
	};
	let isProcessing = false; // 用于跟踪是否正在处理
	const toDIYtripOrTripRecommend = async () => {
		if (isProcessing) return; // 如果已经在处理，则直接返回，防止重复点击

		if (selectedDestinations.value.length > 0) {
			console.log("行程创建:", selectedDestinations.value);
			const isAll = JSON.stringify(selectedDestinations.value);

			// 显示加载指示器
			uni.showLoading({
				title: '正在创建',
				mask: true
			});

			try {
				isProcessing = true; // 标记为正在处理

				const data = await GetgetRecommendation(isAll);
				console.log('推荐商品', data);

				// 导航到相应页面并隐藏加载指示器
				const navigateUrl = data.data ?
					`/homeSubpages/customize/tripRecommend/tripRecommend?selecttrip=${encodeURIComponent(isAll)}` :
					`/homeSubpages/customize/DIYtrip/DIYtrip?selecttrip=${encodeURIComponent(isAll)}`;

				setTimeout(() => {
					uni.navigateTo({
						url: navigateUrl
					});
					uni.hideLoading();
					isProcessing = false; // 操作完成后取消标记
				}, 500); // 设置适当的延时以确保 loading 效果可见

			} catch (error) {
				// 错误处理
				console.error('请求失败:', error);
				uni.showToast({
					title: '系统错误',
					icon: 'none'
				});
				uni.hideLoading();
				isProcessing = false; // 发生错误后取消标记
			}
		} else {
			// 当选择的目的地为空时
			uni.showToast({
				title: '请选择目的地',
				icon: 'none'
			});
			uni.hideLoading();
		}
	};
</script>

<style lang="scss" scoped>
	.WhereTo {
		width: 100%;
		height: 100vh;
		padding: 34rpx;
		box-sizing: border-box;

		.header {
			font-size: 50rpx;
			font-weight: bold;
		}

		.content-box {
			margin-top: 40rpx;
			width: 100%;

			.itembox {
				display: flex;
				white-space: nowrap;
				overflow-x: auto;

				/* 确保内容超出时可以滚动 */
				.header-scroll-box {
					display: flex;

					.header-card {
						min-width: 380rpx;
						min-height: 200rpx;
						margin-right: 20rpx;
						/* 添加右侧间距 */
						color: #fff;
						display: flex;
						flex-direction: column;
						padding: 20rpx;
						box-sizing: border-box;
						border-radius: 10rpx;

						&.active-card {
							opacity: 0.9; // 选中状态半透明效果
							border: 4rpx solid #03a9f4;
						}

						.title {
							font-size: 32rpx;
							font-weight: bold;
						}

						.describe {
							font-size: 24rpx;
							margin-top: 10rpx;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 3;
							overflow: hidden;
							text-overflow: ellipsis;


						}
					}
				}
			}

			.itemboy {
				width: 100%;
				height: 55vh;
				margin-top: 20rpx;
				overflow-y: auto;
				transition: all 0.5s;

				.loopCard {
					width: 100%;
					border: 1rpx solid #dedede;
					margin-top: 20rpx;
					padding: 20rpx;
					box-sizing: border-box;
					border-radius: 14rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					image {
						width: 200rpx;
						height: 200rpx;
						border-radius: 14rpx;
					}

					.container-box {
						display: flex;
						flex-direction: column;
						width: 48%;

						.title {
							font-size: 34rpx;
							font-weight: bold;
						}

						.describe {
							color: #6d6d6d;
							margin-top: 20rpx;
							font-size: 24rpx;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;
							text-overflow: ellipsis;
						}
					}

					.radio {}

				}

				.NoInfo {
					width: 100%;
					display: flex;
					justify-content: center;
					padding: 50rpx 0 0 0;
				}
			}

		}

		.footer-button {
			width: 100%;
			background-color: #fff;
			position: fixed;
			bottom: 0;
			right: 0;
			left: 0;
			display: flex;
			gap: 18rpx;
			justify-content: center;
			padding: 25rpx 40rpx 70rpx 40rpx;
			box-sizing: border-box;
			border-top: 1rpx solid #f1f1f1;
			flex-direction: column;

			.header-box {
				display: flex;
				align-items: center;

				>text {
					width: 44%;
					color: #6d6d6d;
				}

				.itembox {
					display: flex;
					white-space: nowrap;
					overflow-x: auto;

					.selected-card {
						display: flex;
						align-items: center;
						gap: 20rpx;

						.card {
							border-radius: 10rpx;
							border: 1rpx solid #000;
							display: flex;
							align-items: center;
							justify-content: space-around;
							gap: 16rpx;
							padding: 10rpx;
							box-sizing: border-box;

							.Number {
								color: #790000;
							}

							.destination {
								color: #000;
								font-size: 28rpx;
							}

							.cancel {
								font-size: 50rpx;
								color: #6d6d6d;
								transform: rotate(45deg);
								line-height: 12rpx;
							}
						}
					}
				}
			}


			.button {
				width: 100%;
				height: 100rpx;
				background-color: #000;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 10rpx;
			}
		}
	}
</style>